package com.newtribe.security;

import java.security.* ;
import javax.crypto.KeyAgreement;
import javax.crypto.spec.DHParameterSpec;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.SecretKey;

import javax.net.ssl.*;


/**
 * <p> </p>
 * <p>Description: Innovatation method</p>
 * <p>Copyright: Copyright (c)  newtribe innovation 2005</p>
 * <p> </p>
 * @author fuwei
 * @version 1.0
 */

public class KeyAgreementTest {
  public KeyAgreementTest() {
  }
  public static void main(String[] args) throws Exception {

    KeyAgreement() ;

  }
  static void p(byte[] b) {
    int len = 0 ;
    for(int i= 0 ;i <b.length ;i++) {
      len ++ ;
       int m  = (b[i] & 0xff);
       System.out.print(Integer.toHexString(m) +":");
    }
    System.out.println("\r\n =========================length:"+len);

  }

  public static void KeyAgreement()throws Exception  {
    KeyPair alice = DH();
    KeyPair bob = DH2(alice.getPublic());

    KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH");
    bobKeyAgree.init(bob.getPrivate());
    bobKeyAgree.doPhase(alice.getPublic(), true);
    SecretKey bobDesKey = bobKeyAgree.generateSecret("DES");
    System.out.println("--------------bob secret:");
    p(bobDesKey.getEncoded()) ;





    KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH");
    aliceKeyAgree.init(alice.getPrivate());
    aliceKeyAgree.doPhase(bob.getPublic(), true);
  
    SecretKey aliceDesKey = aliceKeyAgree.generateSecret("DES");
    System.out.println("--------------alice secret:");
    p(bobDesKey.getEncoded()) ;


  }
  public static KeyPair DH() throws Exception {
    System.out.println("ALICE: ���� alice DH �� ...");
    KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH");
    aliceKpairGen.initialize(1024);
    KeyPair aliceKpair = aliceKpairGen.generateKeyPair();
    PrivateKey prikey =aliceKpair.getPrivate() ;
    PublicKey  pubKey =aliceKpair.getPublic() ;
    return aliceKpair ;
//    byte[] bPriKey = prikey.getEncoded() ;
//    byte[] bPubKey = pubKey.getEncoded() ;
//    p(bPriKey) ;
//    p(bPubKey) ;

  }
  public static KeyPair DH2(PublicKey alicePubKey) throws Exception {
        System.out.println("ALICE: ���� bob DH �� ...");
  // DHParameterSpec dhParamSpec = ( (DHPublicKey) alicePubKey).getParams();
    KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH");
    bobKpairGen.initialize(1024);
  //  bobKpairGen.initialize(dhParamSpec);
    KeyPair bobKpair = bobKpairGen.generateKeyPair();

    return bobKpair ;

  }



}